﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using JYH.Data;
using Newtonsoft.Json;
using JYH.Model;
using JYH.DataAccess;
using JYH.Framework;
using JYH.Model.API;
using System.IO;
using System.Data;

namespace JYH.Business
{
    /// <summary>
    ///  WmsReciveItem
    /// </summary>
    public class WmsReciveItemBLL : BusinessBase<WmsReciveItem>
    {
        /// <summary>
        ///  WmsReciveItem
        /// </summary>
        public WmsReciveItemBLL()
        {
            myDataBase = DB.D();
            this.SqlSelect = @"; Select WmsReciveItem.*,BasMaterialInfo.MaterialNO,BasMaterialInfo.MaterialDesc,
                                           BasMaterialInfo.Humidity,BasMaterialInfo.MaterialName,BasPartnerInfo.PartnerID,
                                           BasPartnerInfo.PartnerNO,BasPartnerInfo.PartnerName,WmsReciveOrderInfo.ReciveOrderNO
                                           From WmsReciveItem
                                           inner join WmsReciveOrderInfo on WmsReciveOrderInfo.ReciveOrderID=WmsReciveItem.ReciveOrderID
                                           inner join BasMaterialInfo on WmsReciveItem.MaterialID=BasMaterialInfo.MaterialID
                                           left join BasPartnerInfo on WmsReciveOrderInfo.PartnerID=BasPartnerInfo.PartnerID";
        }

        /// <summary>
        /// 收料明细导入
        /// </summary>
        /// <param name="table">上传数据</param>
        /// <param name="reciveOrderID">主档ID</param>
        /// <param name="message"></param>
        /// <returns></returns>
        public bool FileDataTable(DataTable table, string reciveOrderID, ref ResponseJson<WmsReciveItem> message)
        {
            Database db = DB.D();
            db.BeginTransaction();
            StringBuilder sb = new StringBuilder();
            Sql sql = new Sql();
            string Msg = string.Empty;
            List<WmsReciveItem> wmsReciveItems = new List<WmsReciveItem>();
            try
            {
                string MaterialNO = "";
                string PartnerNO = "";
                int MIndex = -1;
                int PIndex = -1;
                if (table == null || table.Rows.Count == 0)
                {
                    message.Code = 500;
                    message.Message = "Excel 文件为空或格式错误";
                    db.AbortTransaction();
                    return false;
                }
                foreach (DataRow row in table.Rows)
                {
                    MaterialNO += "'" + row["物料料号"]?.ToString().Trim() + "',";
                    PartnerNO += "'" + row["供应商编号"]?.ToString().Trim() + "',";
                }
                MaterialNO = MaterialNO.Substring(0, MaterialNO.Length - 1);
                PartnerNO = PartnerNO.Substring(0, PartnerNO.Length - 1);
                //获取物料列表
                var materialList = new BasMaterialInfoBLL().NotPagedQuery(new Sql().Where(" BasMaterialInfo.MaterialNO in (" + MaterialNO + ")"), out Msg, "BasMaterialInfo.MaterialNO");
                if (!materialList.Any())
                {
                    message.Message = "物料编号列表为空，请检查";
                    db.AbortTransaction();
                    return false;
                }
                //  获取供应商列表
                var partnerList = new BasPartnerInfoBLL().NotPagedQuery(new Sql().Where(" BasPartnerInfo.PartnerNO in (" + PartnerNO + ")"), out Msg, "BasPartnerInfo.PartnerNO");
                if (!materialList.Any())
                {
                    message.Message = "供应商列表为空，请检查";
                    db.AbortTransaction();
                    return false;
                }
                var ReciveInfo = new WmsReciveOrderInfoBLL().GetSingeModel(new Sql().Where(" WmsReciveOrderInfo.ReciveOrderID = '" + reciveOrderID + "'"));
                if (ReciveInfo == null)
                {
                    message.Message = "收料单号不存在";
                    db.AbortTransaction();
                    return false;
                }
                for (int i = 0; i < table.Rows.Count; i++)
                {
                    MIndex = -1;
                    PIndex = -1;
                    WmsReciveItem wmsRecive = new WmsReciveItem();
                    MIndex = materialList.FindIndex(x => x.MaterialNO == table.Rows[i]["物料料号"]?.ToString().Trim());
                    if (MIndex > -1)
                    {
                        wmsRecive.MaterialID = materialList[MIndex].MaterialID;
                    }
                    else
                    {
                        message.Message = "第" + (i + 1) + "行,物料编号在系统中不存在";
                        db.AbortTransaction();
                        return false;
                    }
                    if (materialList[MIndex].RState == "99")
                    {
                        message.Message = "第" + (i + 1) + "行,物料编号在系统中已删除";
                        db.AbortTransaction();
                        return false;
                    }

                    if (wmsReciveItems.FindIndex(x => x.MaterialID == materialList[MIndex].MaterialID) > -1)
                    {
                        message.Message = "第" + (i + 1) + "行,物料编号在表格中有重复.";
                        db.AbortTransaction();
                        return false;
                    }
                    PIndex = partnerList.FindIndex(x => x.PartnerNO.ToUpper() == table.Rows[i]["供应商编号"]?.ToString().ToUpper().Trim());
                    if (PIndex < 0)
                    {
                        message.Message = "第" + (i + 1) + "行,供应商编号系统中不存在";
                        db.AbortTransaction();
                        return false;
                    }
                    if (ReciveInfo.PartnerID != partnerList[PIndex].PartnerID)
                    {
                        message.Message = "请导入收料单:" + ReciveInfo.ReciveOrderNO + "的供应商的明细.";
                        db.AbortTransaction();
                        return false;
                    }
                    wmsRecive.ReciveOrderID = reciveOrderID;
                    wmsRecive.ReciveItemID = Guid.NewGuid().ToString();
                    decimal rQty = 0; // 默认值
                    string rvalue = table.Rows[i]["物料总数"]?.ToString().Trim();
                    if (!string.IsNullOrWhiteSpace(rvalue) && decimal.TryParse(rvalue, out rQty))
                    {
                        // 成功转换，可以使用 receiveQty
                        wmsRecive.ReciveQty = rQty;
                    }
                    else
                    {
                        // 转换失败处理，例如记录日志或提示错误信息
                        message.Message = $"第 {i + 1} 行：物料总数格式不正确";
                        db.AbortTransaction();
                        return false;
                    }
                    decimal PQty = 0; // 默认值
                    string Pvalue = table.Rows[i]["单盘标准"]?.ToString().Trim();
                    if (!string.IsNullOrWhiteSpace(Pvalue) && decimal.TryParse(Pvalue, out PQty))
                    {
                        // 成功转换，可以使用 receiveQty
                        wmsRecive.PackQty = PQty;
                    }
                    else
                    {
                        wmsRecive.PackQty = wmsRecive.ReciveQty;
                    }
                    wmsRecive.LabelQty = wmsRecive.ReciveQty;
                    if (!string.IsNullOrWhiteSpace(table.Rows[i]["物料批号"]?.ToString().Trim()))
                    {
                        wmsRecive.BatchNO = table.Rows[i]["物料批号"]?.ToString().Trim();
                    }
                    wmsRecive.CreateUser = SysUserInfoBLL.GetCookieUser().UserName;
                    wmsReciveItems.Add(wmsRecive);
                    message.TotalCount += 1;
                }

                foreach (WmsReciveItem item in wmsReciveItems)
                {
                    sb.Append(BusinessTool.GetInsertSql(item));
                }
                db.Execute($"Delete from WmsReciveItem where WmsReciveItem.ReciveOrderID='{reciveOrderID}'");
                if (sb.Length > 0)
                {
                    db.Execute(sb.ToString());
                }
            }
            catch (Exception ex)
            {
                message.Message = ex.Message;
                db.AbortTransaction();
                return false;
            }
            db.CompleteTransaction();
            return true;
        }
    }
}